package com.meeting.y.controller;

import com.jfinal.core.ActionKey;
import com.jfinal.core.Controller;
import com.jfinal.core.paragetter.Para;
import com.jfinal.kit.PathKit;
import com.jfinal.kit.Ret;
import com.jfinal.log.Log;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.swagger.annotation.ActionApi;
import com.jfinal.swagger.annotation.Api;
import com.jfinal.swagger.annotation.Param;
import com.jfinal.swagger.annotation.Params;
import com.jfinal.upload.UploadFile;
import com.meeting.y.model.*;
import com.meeting.y.util.*;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.*;

@Api(remark="YpaperController，小程序 调查问卷接口", sort=1)
public class YpaperController extends Controller {
    private static final Logger logger = LoggerFactory.getLogger(YpaperController.class);


    /**
     * 获取问卷题目数量
     * "code":0,"message":"返回成功"}
     */
    @ActionApi(remark = "获取问卷题目数量")
    @Params({
            @Param(name = "surveyid", remark = "问卷id", defaultValue = "8")
    })
    public void paper_quessize(@Para("surveyid") Integer surveyid) {

        Record record = Db.findFirst("select count(1) count from ques where surveyid = ?",surveyid);

        renderJson(Ret.ok("code", 0).set("message", "返回成功").set("data", record.getInt("count")));
    }

    /**
     * 获取问卷用户栏目分数
     * "code":0,"message":"返回成功"}
     */
    @ActionApi(remark = "获取问卷用户栏目分数")
    @Params({
            @Param(name = "surveyid", remark = "问卷id", defaultValue = "8"),
            @Param(name = "userid", remark = "用户id", defaultValue = "1")
    })
    public void paper_usersurveycount(@Para("userid") Integer userid,@Para("surveyid") Integer surveyid,
        @Para("answerrecordid")Integer answerrecordid) {
        Map _result = new HashMap();

        List<Record> result = new PaperDao().getUserPagerCount(userid,surveyid,answerrecordid);
        List<Record> ageresult = new PaperDao().getUserPagerAgeCount(userid,surveyid,answerrecordid);
        _result.put("count",result);
        _result.put("agecount",ageresult);

        renderJson(Ret.ok("code", 0).set("message", "返回成功").set("data", _result));
    }

    /**
     * 获取线图数据
     * "code":0,"message":"返回成功"}
     */
    @ActionApi(remark = "获取线图数据")
    @Params({
            @Param(name = "surveyid", remark = "问卷id", defaultValue = "8"),
            @Param(name = "userid", remark = "用户id", defaultValue = "1")
    })
    public void paper_chartdetail(@Para("surveyid") Integer surveyid,
                                   @Para("answerrecordid")Integer answerrecordid) {

        List<Map> _resultlist = new LinkedList<Map>();
        List<Record> result = new PaperDao().getTypesBySurveyid(surveyid);
        for(Record record:result) {
            Map _result = new HashMap();
            String showname = record.getStr("showname");
            Integer val = NumberTool.safeToInteger(record.getStr("val"),-1);
            List<Record> quesdetail = new PaperDao().getQuesDetailByType(answerrecordid,val);
            List<String> ques_categories = new LinkedList<String>();
            List<Integer> ques_data = new LinkedList<Integer>();
            List<String> ques_desc = new LinkedList<String>();
            for(Record record1:quesdetail){
                ques_categories.add(record1.getStr("monthage")+"月");
                ques_data.add(record1.getInt("optionvalue"));
                ques_desc.add(record1.getStr("quescontent"));
            }
            _result.put("showname", showname);
            _result.put("ques_categories", ques_categories);
            _result.put("ques_data", ques_data);
            _result.put("ques_desc", ques_desc);
            _resultlist.add(_result);
        }

        List<Record> ageColumnsCount = new PaperDao().getAgeColumnsCount(surveyid,answerrecordid);
        //进行结构拆分，画柱状图。
        /*
        main: {
      title: '总成交量',
      data: [15, 20, 45, 37],
      categories: ['2012', '2013', '2014', '2015']
        },
         */
        List<Map> _barresultlist = new LinkedList<Map>();
        //先归类放入map：list中
//        再循环 拼接数据放入
        Map<String,List<Record>> listMap = new LinkedHashMap<>();
        for(Record record:ageColumnsCount){
            String columnname = record.getStr("columnname");
            List<Record> list = listMap.get(columnname);
            if(list == null){
                list = new LinkedList<>();
                listMap.put(columnname,list);
            }
            list.add(record);
        }
        for(String key :listMap.keySet()){
            Map barmap = new HashMap();
            barmap.put("title",key);
            List<Record> list = listMap.get(key);
            Object [] monthage =  RecordUtil.JsontoArray(list,"monthage","","月");
            Object [] date = RecordUtil.JsontoArray(list,"count");
            barmap.put("data",date);
            barmap.put("categories",monthage);
            _barresultlist.add(barmap);
        }

        Map _data = new HashMap();
        _data.put("linechartlist",_resultlist);
        _data.put("barchartlist",_barresultlist);
        renderJson(Ret.ok("code", 0).set("message", "返回成功").set("data", _data));
    }

    /**
     * 获取问卷用户栏目分数
     * "code":0,"message":"返回成功"}
     */
    @ActionApi(remark = "导出答题详细")
    @Params({
            @Param(name = "surveyid", remark = "问卷id", defaultValue = "8"),
            @Param(name = "userid", remark = "用户id", defaultValue = "1")
    })
    public void paper_exportdetail(@Para("userid") Integer userid,@Para("surveyid") Integer surveyid,
                                      @Para("answerrecordid")Integer answerrecordid) {
        String name = "/筱薇教育评估报告单.xlsx";//"/答题明细-开发中.xlsx"

        String _file = PathKit.getRootClassPath() +name;
        List<Record> quesdetail9 = new PaperDao().getQuesDetailByType_Export(answerrecordid,9);
        List<Record> quesdetail10 = new PaperDao().getQuesDetailByType_Export(answerrecordid,10);
        List<Record> quesdetail11 = new PaperDao().getQuesDetailByType_Export(answerrecordid,11);
        //todo 处理excel。获取题目名称和得分情况 填入到excel中。保存并 返回。
        String filePath = "";
        try {
            XSSFWorkbook workbook = new XSSFWorkbook(_file);
            XSSFSheet sheet = workbook.getSheetAt(0);
            XSSFSheet sheet1 = workbook.getSheetAt(1);
            XSSFSheet sheet2 = workbook.getSheetAt(2);
            String[] keysort = new String[]{"quescontent","optionvalue"};
            ExcelUtil.writeExcel(sheet,quesdetail9,2,1,keysort);
            ExcelUtil.writeExcel(sheet1,quesdetail10,2,1,keysort);
            ExcelUtil.writeExcel(sheet2,quesdetail11,2,1,keysort);
            OutputStream out = null;
            String newFileNAme = "/筱薇教育评估报告单_"+new PaperDao().getAnswerUserName(answerrecordid)+".xlsx";
            filePath = PathKit.getRootClassPath() +newFileNAme;
            try {
                out = new FileOutputStream(filePath);
                workbook.write(out);
                out.close();
            } catch (Exception e){
                e.printStackTrace();
            }
        }catch (Exception e){
            logger.error("导出异常",e);
        }

        renderFile(new File(filePath));
    }

    /**
     * 获取问卷 问题 选项 答案 关联关系
     * "code":0,"message":"返回成功"}
     */
    @ActionApi(remark = "取问卷 问题 选项 答案 关联关系")
    @Params({
            @Param(name = "surveyid", remark = "问卷id", defaultValue = "8")
    })
    public void paper_rela(@Para("surveyid") Integer surveyid){
        List<Record> result = new PaperDao().getPaperRela(surveyid);

        Map resultmap = new HashMap();
        Map answer_usermap = new HashMap();
        for(Record record:result){
            Integer answerid = record.getInt("answerid");
            Integer userid = record.getInt("userid");
            answer_usermap.put(answerid,userid);
        }
        resultmap.put("answer_user",answer_usermap);
        renderJson(Ret.ok("code", 0).set("message", "返回成功").set("data",resultmap ));
    }

    public void survey_delete(@Para("surveyid") Integer surveyid){
        List<Record> records = PaperDao.dao.getPaperRela(surveyid);
        deleteQues(surveyid,records);
        if(records.size()==0){
            Db.deleteById("survey", "surveyid",surveyid);
        }else {
            PaperDao.dao.deleteObjIn("survey", "surveyid",
                    RecordUtil.recordlistToList(records, "surveyid").toArray(new Integer[0]));
        }
        renderJson(Ret.ok("code", 0).set("message", "返回成功"));
    }

    public void deleteQues(Integer surveyid,List<Record> records){
        // 需要级联删除4个表 c.surveyid,a.quesid,a.optionid,b.answerid
        PaperDao.dao.deleteObjIn("answer","answerid",
                RecordUtil.recordlistToList(records,"answerid").toArray(new Integer[0]));
        PaperDao.dao.deleteObjIn("`option`","optionid",
                RecordUtil.recordlistToList(records,"optionid").toArray(new Integer[0]));
        PaperDao.dao.deleteObjIn("ques","quesid",
                RecordUtil.recordlistToList(records,"quesid").toArray(new Integer[0]));
    }

    /**
     * 获取正在答题位置
     * "code":0,"message":"返回成功"} firstques quesorder， doingques true/false
     */
    @ActionApi(remark = "获取正在答题位置")
    @Params({
            @Param(name = "surveyid", remark = "问卷id", defaultValue = "8")
    })
    public void getdoingsurvey(@Para("surveyid") Integer surveyid){
        Integer userid =  getAttrForInt("userid");//
        Record record = PaperDao.dao.getDoingRedordOrder(surveyid,userid);
        Integer quesOrder = record.getInt("maxquesorder");
        Integer maxrecordid = record.getInt("maxrecordid");
        Map resultmap = new HashMap();
        if(quesOrder != null && quesOrder > 0){
            resultmap.put("firstques",quesOrder );
            resultmap.put("answerrecordid",maxrecordid );
            resultmap.put("doingques",true);
        }else {
            resultmap.put("firstques",0 );
            resultmap.put("answerrecordid",0);
            resultmap.put("doingques",false);
        }
        renderJson(Ret.ok("code", 0).set("message", "返回成功").set("data",resultmap ));

    }

    public void saveanswerrecore(@Para("surveyid") Integer surveyid){
        Integer userid =  getAttrForInt("userid");//
        Integer answerrecordid = getParaToInt("answerrecordid",0);
        Map resultmap = new HashMap();

        if(answerrecordid>0){
            AnswerRecord answerRecord = AnswerRecord.dao.findById(answerrecordid);
            answerRecord.setStatus(2);//完成
            answerRecord.setEndtime(new Date());
            AnswerRecord.dao.saveOrUpdateAnswerrecord(answerRecord);
        }else {
            AnswerRecord answerRecord = new AnswerRecord();
            answerRecord.setModifyTime(new Date());
            answerRecord.setStarttime(new Date());
            answerRecord.setUserid(userid);
            answerRecord.setStatus(1);//1 答题中
            answerRecord.setSurveyid(surveyid);
            AnswerRecord.dao.saveOrUpdateAnswerrecord(answerRecord);
            resultmap.put("answerrecordid", answerRecord.getId());
        }
        renderJson(Ret.ok("code", 0).set("message", "返回成功").set("data",resultmap ));

    }

    public void upload() {
        UploadFile ufile = getFile();//必须先调用改方法，否则，其他参数无法获取到，非常的坑。搞了好久
        if (ufile == null) {
            renderJson(Ret.fail().set("message", "无法找到文件"));
            return;
        }

        //題號	舊題號	題目		月齡 栏目
        String[] Class_PROPERTY = new String[]{"題號", "題目","月齡","栏目"};

        Integer surveyid = getParaToInt("surveyid");
        if(surveyid==null){
            surveyid = 16;
            return;
        }

        File file = ufile.getFile();

//        String _filepath = "C:\\work\\git\\one-JFinal-vue-element-admin\\";
//        String _filename = "1_PCDC新舊題號對照及月齡.xlsx";

//        File file = new File(_filepath+_filename);
        try {
            boolean covered = getParaToBoolean("covered",true);

            FileInputStream _in = new FileInputStream(file);
            Workbook workbook = UploadClassesController.parse(_in, "xlsx");
            Sheet sheet = workbook.getSheetAt(0);
            /*从B2开始读
             */

            //必须表头字段，动态表头，允许前三行任一行.headline 从开始的，行数减1
            Integer[] headNums = OfficeUtil.getHeadNums(1,Class_PROPERTY, sheet);
            if (headNums == null) {
                renderJson(Ret.fail().set("message", "表头不满足,请使用模板"));
                return;
            }

            if(covered){
                List<Record> records = PaperDao.dao.getPaperRela(surveyid);
                deleteQues(surveyid,records);
            }

            Integer userid = 1;
            int rowNum = sheet.getPhysicalNumberOfRows();
            Map _columntype = RecordUtil.recordlistToMap(
                    MeetingEnum.dao.findMeetingenumList("quescolumns"),"name","value");
            Integer maxvalue = null;
            Integer maxsort = null;

            for (int rowIndex = 2; rowIndex < rowNum; rowIndex++) {
                try {
                    //信息验证
                     Log.getLog(this.getClass()).debug("------rowIndex" + rowIndex );
                    StringBuffer message = new StringBuffer();
                    Row row = sheet.getRow(rowIndex);
                    if (row == null) {
                        continue;
                    }
                    int cellNum = row.getPhysicalNumberOfCells();
                    if (cellNum > 0) {

                        Cell cell = row.getCell(headNums[0]);//序号 非必填

                        Cell cell1 = row.getCell(headNums[1]);//问题 题目 必填
//                        Cell cell2 = row.getCell(headNums[2]);//答案 必填 英文逗号分隔
//                        Cell cell3 = row.getCell(headNums[3]);//正确答案 不必填，目前没用
                        Cell cell4 = row.getCell(headNums[2]);//月龄
                        Cell cell5 = row.getCell(headNums[3]);//栏目 不必填

                        String no = OfficeUtil.getCellValue(cell);
                        String quescontent = OfficeUtil.getCellValue(cell1);
                        String options = "是,否";//OfficeUtil.getCellValue(cell2);
                        String monthage = OfficeUtil.getCellValue(cell4);
                        String columntypename = OfficeUtil.getCellValue(cell5);
                        Integer colmntypeid = null;

                        if(_columntype.containsKey(columntypename)){
                            colmntypeid = NumberTool.safeToInteger(_columntype.get(columntypename),null);
                        }else{
                            Record maxrecord = MeetingEnum.dao.findMeetingenumMax("quescolumns");
                            Integer newvalue = NumberTool.safeToInteger(maxrecord.getStr("mvalue"),1);
                            Integer newsort = NumberTool.safeToInteger(maxrecord.getStr("msort"),1);

                            if(maxvalue ==null){ maxvalue = newvalue;}
                            if(maxsort ==null){ maxsort = newsort;}

                            MeetingEnum meetingEnum = new MeetingEnum();
                            meetingEnum.setMeetingEnumVal( ++maxvalue + "");
                            meetingEnum.setMeetingEnumSort( ++maxsort + "");
                            meetingEnum.setMeetingEnumKey("quescolumns");
                            meetingEnum.setMeetingEnumShowname(columntypename.trim());
                            meetingEnum.setUserId(userid);
                            meetingEnum.setModifyTime(new Date());
                            meetingEnum.save();
                            _columntype.put(columntypename.trim(),maxvalue);
                            colmntypeid = maxvalue;
                        }

                        Record ques = new Record();
                        ques.set("quescontent",quescontent);
                        ques.set("quesorder",NumberTool.safeToInteger(no,1));
                        ques.set("quesrequired",1);
                        ques.set("surveyid",surveyid);
                        ques.set("monthage",monthage);
                        ques.set("questypeid",1);//单选题
                        ques.set("columntype",colmntypeid);

                        Integer quesid = PaperDao.dao.saveQues(ques);
                        for(String optiontxt:options.split(",")){
                            Record option = new Record();
                            option.set("optioncontent",optiontxt);
                            option.set("quesid",quesid);
                            PaperDao.dao.saveOption(option);
                        }

                    }
                } catch (Exception e) {
                    Log.getLog(this.getClass()).debug("------rowIndex" + rowIndex);
                    e.printStackTrace();
                    break;
                }
            }
            

        } catch (Exception e) {
            Log.getLog(this.getClass()).debug("导入题目异常");
            e.printStackTrace();
            renderJson(Ret.fail().set("message", "导入题目异常"));
        }
        renderJson(Ret.ok("code", 0).set("message", "返回成功"));
    }



}
